package pl.un4giv3n.mightvsmagic.action;

import javax.persistence.EntityManager;

import pl.un4giv3n.mightvsmagic.entity.Message;
import pl.un4giv3n.mightvsmagic.entity.User;

public class ShowMessageAction extends PersistenceAction {
	private static final long serialVersionUID = 1L;
	private long messageId;
	private Message message;
	
	@Override
	public String execute() {
		EntityManager entityManager = getEntityManager();
		User user = getSessionUser(entityManager);
		if(user == null){
			entityManager.close();
			return LOGIN;
		}
		message = entityManager.find(Message.class, messageId);
		if(message == null){
			addActionError("Nie znaleziono wiadomości");
			entityManager.close();
			return INPUT;
		}
		if(message.getSenderId() != getSessionUserId().longValue() && message.getReciverId() != getSessionUserId().longValue())	{
			addActionError("Nie jesteś uprawiony do oglądania tej wiadomości");
			entityManager.close();

			return INPUT;
		}
		if(message.getReciverId() == getSessionUserId().longValue()){
			message.setReciverRead(true);
			entityManager.getTransaction().begin();
			entityManager.merge(message);
			entityManager.flush();
			entityManager.getTransaction().commit();
		}
		entityManager.close();
		return SUCCESS;
	}

	public long getMessageId() {
		return messageId;
	}

	public void setMessageId(long messageId) {
		this.messageId = messageId;
	}

	public Message getMessage() {
		return message;
	}
	
}
